const jwt = require('jsonwebtoken');

exports = module.exports = server => {
	server.add('app', (app, next) => {
		app.text = (text) => {
			if (typeof text !== 'string' && typeof text.toString === 'function')
				text = text.toString();
			app.setHeader('Content-Type', 'text/plain;charset=utf-8');
			app.write(text);
		}

		app.json = (data) => {
			data = JSON.stringify(data);
			app.setHeader('Content-Type', 'application/json;charset=utf-8');
			app.write(data);
		}

		next();
	});

	server.add('json', async (app, next) => {
		if (app.req.headers['content-type']?.includes('application/json')) {
			app.fields = await (() => new Promise((resolve, reject) => {
				app.req.setEncoding('utf8');

				const chunks = [];
				app.req.on('data', chunk => {
					try {
						chunks.push(chunk);
					} catch (err) {
					}
				});
				app.req.on('end', () => {
					try {
						/*
						const fields = chunks.reduce((fields, chunk) => {
							return {
								...fields, ...JSON.parse(chunk)
							};
						}, {});
						*/
						const fields = chunks.length ? JSON.parse(chunks.join()) : {};
						resolve(Object.assign(app.fields, fields));
					} catch (err) {
						console.log(err);
					}
				});
				app.req.on('error', err => {
					reject(err);
				});
			}))();
		}

		next();
	});

	server.add('cors', (app, next) => {
		app.setHeader("Access-Control-Allow-Origin", "*");
		app.setHeader('Access-Control-Allow-Methods', 'PUT,GET,POST,DELETE,OPTIONS');
		app.setHeader('Access-Control-Allow-Headers', ['Authorization', 'Content-Type']);

		next();
	});

	server.add('jwt', (app, next) => {
		let token = app.fields.token || app.req.headers.authorization || '';

		if (token.startsWith('Bearer ')) token = token.slice(7, token.length).trimLeft();

		try {
			app.auth = jwt.verify(token, 'wiseidc');
			next();
		} catch (err) {
			app.error('', { status: 401 });
		}
	});

	server.use(['app', 'json', 'cors']);
};
